// node version v16.7.0+
if (!process.env.PWD.endsWith('aurora-pack')) {
	throw '你必须在 aurora-pack 目录下执行这个脚本';
}

async function printPromise(text) {
	console.log(text);
}

async function errorPromise(text, err) {
	console.error(text + '\n\n', err);
}

let fsp = require('fs/promises');
let util = require('util');

async function checkDirExists(path, errText) {
	return fsp.stat(path, {})
		.catch(err => {
			console.error(util.format('目录: %s 无法读取:\n%s\n', err.path, errText));
			return Promise.reject(errText);
		});
}

printPromise('1.  清空 res 目录')
	.then(() => fsp.rm('res', { recursive: true, force: true }))
	.then(() => fsp.mkdir('res'))

	.then(() => printPromise('2.  检查必要文件'))
	.then(() => Promise.all(
		[
			checkDirExists('../aurora-front/dist',
					'你需要在 ../aurora-front/ 目录下执行 npm run build 打包展示框架'),
			checkDirExists('../aurora-front/dist-comp',
					'你需要在 ../aurora-front/ 目录下执行 npm run dll 打包展示模块'),
			checkDirExists('../aurora-monitor/dist',
					'你需要在 ../aurora-monitor/ 目录下执行 npm run build 打包监控框架'),
			checkDirExists('../aurora-monitor/dist-comp',
					'你需要在 ../aurora-monitor/ 目录下执行 npm run dll 打包监控模块')
		])
	)

	.then(() => printPromise('3.  从 aurora-front 目录中复制展示前端框架文件'))
	.then(() => fsp.cp(
			'../aurora-front/dist/scene',
			'./res/public/scene',
			{recursive : true, force : true}
	))

	.then(() => printPromise('4.  从 aurora-front 目录中复制展示前端模块文件'))
	.then(() => fsp.cp(
			'../aurora-front/dist-comp/aurora-res',
			'./res/package',
			{recursive : true, force : true}
	))

	.then(() => printPromise('5.  从 aurora-monitor 目录中复制监控前端模块文件'))
	.then(() => fsp.cp(
			'../aurora-monitor/dist/_bundle',
			'./res/public/_bundle',
			{recursive : true, force : true}
	))
	.then(() => fsp.cp(
			'../aurora-monitor/dist/aurora',
			'./res/public/aurora',
			{recursive : true, force : true}
	))

	.then(() => printPromise('6.  从 aurora-monitor 目录中复制监控前端模块文件'))
	.then(() => fsp.cp(
			'../aurora-monitor/dist-comp',
			'./res/package',
			{recursive : true, force : true}
	))

	.then(() => printPromise('7.  从 aurora-static 目录中复制静态文件'))
	.then(() => fsp.cp(
			'../aurora-static',
			'./res',
			{recursive : true, force : true}
	))

	.then(() => printPromise('8.  剩余检查'))
	// TODO 当前没有特殊检查

	.then(() => printPromise('\n\n运行成功 | Build Success'))
	.then(() => printPromise('\n\n后续将 ./res 目录整个复制并 merge 到 Aurora (java) 项目的 res 下即可'))
	.catch((err) => errorPromise('\n\n运行失败 | Build Fail', err))
